/*  
 * i-OSGi - Tunable Bundle Isolation for OSGi
 * Copyright (C) 2011  Sven Schulz
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.iosgi.benchmark;

import java.util.concurrent.TimeUnit;

import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Provides;
import org.apache.felix.ipojo.annotations.Requires;
import org.apache.felix.ipojo.annotations.ServiceProperty;
import org.apache.felix.ipojo.annotations.Validate;
import org.iosgi.Constants;
import org.iosgi.IsolationEnvironment;

/**
 * @author Sven Schulz
 */
@Component(immediate = true)
@Provides(specifications = { PingService.class })
public class PingServiceImpl implements PingService {

	@SuppressWarnings("unused")
	@ServiceProperty(name = Constants.R_OSGI_REGISTRATION)
	private boolean publishRemotely = Boolean.TRUE;

	@ServiceProperty(name = Constants.ENVIRONMENT_ID)
	private String environmentId;

	@Requires(filter = "(& (" + Constants.R_OSGI_REGISTRATION + "=*) ("
			+ Constants.LEVEL + "=0))")
	private IsolationEnvironment ie;

	@Requires(optional = true)
	private PingService[] pingSvcs;

	@Validate
	void activate() {
		environmentId = ie.getId().toString();
	}

	private PingService getPingService(String envId) {
		for (PingService svc : pingSvcs) {
			if (svc.getEnvironmentId().equals(envId)) {
				return svc;
			}
		}
		return null;
	}

	@Override
	public String getEnvironmentId() {
		return environmentId;
	}

	@Override
	public int perform(String targetId, long duration, TimeUnit unit) {
		PingService target = this.getPingService(targetId);
		long deadline = System.currentTimeMillis()
				+ TimeUnit.MILLISECONDS.convert(duration, unit);
		int i = 0;
		while (true) {
			target.ping(i++);
			if (i % 1000 == 0 && deadline < System.currentTimeMillis())
				break;
		}
		return i;
	}

	@Override
	public <T> T ping(T data) {
		return data;
	}

}